import React, { useRef } from 'react'
import {
  TouchableOpacity,
  StyleSheet,
  Image,
  findNodeHandle,
  Alert,
  View,
  GestureResponderEvent,
} from 'react-native' // Import Image from react-native
import { Fonts } from '@/constants/Themes'
import { ThemedText } from '@/components/ThemedText'
import { ThemedView } from '@/components/ThemedView'
import { AntDesign, Entypo, Ionicons } from '@expo/vector-icons'
import { Partition } from './Partition'
import { router } from 'expo-router'

export default function Header({
  title,
  icon,
  ishome = false,
}: {
  title: string
  icon?: string
  ishome?: boolean
}) {
  const back = () => {
    router.back()
  }

  const buttonRef = useRef<View | null>(null)

  const handleMenu = (event: GestureResponderEvent) => {
    console.log(event)

    let { pageX: x, pageY: y } = event.nativeEvent
    Alert.alert('Button clicked!', `Position on screen: ${x}, ${y}`)
  }

  return (
    <>
      <Partition />
      <ThemedView style={styles.header}>
        <ThemedView style={{ flexDirection: 'row' }}>
          {!ishome ? (
            <TouchableOpacity
              onPress={() => back()}
              activeOpacity={0.7}
              style={{ flexDirection: 'row' }}
            >
              <AntDesign
                name="arrowleft"
                size={24}
                color="black"
                style={[{ marginRight: 8 }, Fonts.menutitle]}
              />
              {/* 是否有图标 */}
              {icon ? (
                <Image
                  source={{ uri: icon }}
                  style={styles.icon}
                />
              ) : null}
              {/* 标题 */}
              <ThemedText style={Fonts.menutitle}>{title}</ThemedText>
            </TouchableOpacity>
          ) : (
            // 主页不显示返回按钮
            // 标题
            <ThemedText style={Fonts.menutitle}>{title}</ThemedText>
          )}
        </ThemedView>

        <TouchableOpacity
          style={styles.menuButton}
          onPress={handleMenu}
        >
          <View ref={buttonRef}>
            <Entypo
              name="dots-three-vertical"
              size={24}
              color="black"
            />
          </View>
        </TouchableOpacity>
      </ThemedView>
    </>
  )
}
const styles = StyleSheet.create({
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 20,
    paddingVertical: 4,
    width: '100%',
  },
  menuButton: {
    padding: 10,
  },
  icon: {
    width: 40,
    height: 40,
    borderRadius: 25,
    marginRight: 10,
  },
})
